import 'package:flutter/material.dart';

import 'home.dart';
import 'joke.dart';
import 'random_joke_scope.dart';
import 'random_joke_state.dart';

void main() {
  runApp(const RandomJokeApp());
}

class RandomJokeApp extends StatefulWidget {
  const RandomJokeApp({super.key});

  @override
  State<RandomJokeApp> createState() => _RandomJokeAppState();
}

class _RandomJokeAppState extends State<RandomJokeApp> {
  RandomJokeState _state = const RandomJokeState(isLoading: true);

  @override
  void initState() {
    super.initState();
    _refresh(initialLoad: true);
  }

  Future<void> _refresh({bool initialLoad = false}) async {
    final previousJoke = _state.joke;
    final keepPrevious = !initialLoad && previousJoke != null;

    setState(() {
      _state = _state.copyWith(
        joke: keepPrevious ? previousJoke : null,
        error: null,
        isLoading: true,
        isRefreshing: keepPrevious,
      );
    });

    try {
      final joke = await fetchRandomJoke();
      if (!mounted) {
        return;
      }
      setState(() {
        _state = _state.copyWith(
          joke: joke,
          error: null,
          isLoading: false,
          isRefreshing: false,
        );
      });
    } catch (err) {
      if (!mounted) {
        return;
      }
      setState(() {
        _state = _state.copyWith(
          joke: keepPrevious ? previousJoke : null,
          error: err,
          isLoading: false,
          isRefreshing: false,
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: RandomJokeScope(
        state: _state,
        refresh: () => _refresh(),
        child: const HomeView(),
      ),
    );
  }
}
